<?php
$error =array();
if(!empty($_POST)) {
    $username = isset($_POST['username']) ? trim($_POST['username']) : '';
    $password = isset($_POST['password']) ? $_POST['password'] : '';
    require 'check_form.lib.php';
    if (($result = checkUsername($username)) !== true) $error[] = $result;
    if (($result = checkPassword($password)) !== true) $error[] = $result;
    //表单验证通过，再到数据库中验证；
    if (empty($error)) {
        //连接数据库
        $link = mysqli_connect('localhost', 'root', '', 'user');
        if (!$link) {
            die ('连接数据库失败！' . mysqli_error($link));
        }
//设置字符集，选择数据库
        mysqli_query($link, 'set names utf8');
        mysqli_query($link, 'use user');
//连接数据库；
        //当cookie中存在登入状态；
        if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
            //取出用户名和密码；、
            $username = $_COOKIE['username'];
            $password = $_COOKIE['password'];
            $username = mysqli_real_escape_string($link, $username);
            $sql = "select `id`,`password`,`salt` from `user` where `username`='$username'";


            if ($rst = mysqli_query($link, $sql)) ;
            {
                $row = mysqli_fetch_assoc($rst);
                $password = md5($row['salt'] . md5($password));
                //判断密码是否正确；
                if ($password == $row['password']) {
                    if (isset($_POST['auto_login']) && $_POST['auto_login'] == 'on') {
                        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
                        $password_cookie = md5($row['password'] . md5($ua . $row['salt']));
                        $cookie_expire = time() + 60 * 60 * 24 * 30;//保存一个月；
                        setcookie('username', $username, $cookie_expire);
                        setcookie('password', $password_cookie, $cookie_expire);
                    }


                    //登入成功，保存用户回话；
                    session_start();
                    $_SESSION['userinfo'] = array('id' => $row['id'], 'username' => $username);
                    header('Location: user.php');
                    die;

                }

            }
            $error[] = '用户名不存在或密码错误。';

        }
    }
}
require 'login_html.php';

